package krt.wid.gslzs.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.widget.Button;
import android.widget.Toast;

import com.krt.webapp.R;
import com.krt.webapp.activity.PicSelectActivity;
import com.krt.webapp.activity.ScanActivity;
import com.krt.webapp.until.AppInfo;
import com.krt.webapp.until.BaseUtil;
import com.krt.webapp.until.MyApplication;
import com.krt.webapp.until.SendMsg;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;

import krt.wid.gslzs.base.MApplication;
import krt.wid.gslzs.util.SpUtil;
import lx.lib.mywidgetlib.MWDownloadTask;
import lx.lib.mywidgetlib.MyWeb;
import lx.lib.mywidgetlib.MyWeb.OnWebStaChangeListener;
import lx.lib.update_lib.ToolUpdate_base;
import lx.lib.update_lib.UpdateTask;

public class WebActivity extends AppCompatActivity {

    private static final String TAG = "WebActivity";
    private static final int GET_PIC = 1;
    private static final int GET_SCAN = 2;
    private MyWeb myWeb;
    private BaseUtil baseUtil;
    private int IN_BACK = 1;//是否正在后退
    private String DL_path;//下载路径

    private MyApplication myApplication;
    private ArrayList<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
    private Button button1, refresh;
    private SoundPool pool;
    private int soundid;
    private String MAIN_URL, XG_TOKEN;

    private SpUtil mSpUtil;

    private ToolUpdate_base tUpdate_base;
    private AppInfo appInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏

        mSpUtil = new SpUtil(this);
        baseUtil = new BaseUtil(this);
        dataList = new ArrayList<Map<String, String>>();
        myApplication = new MyApplication(getApplication());
        pool = new SoundPool(10, AudioManager.STREAM_RING, 5);
        soundid = pool.load(this, R.raw.yx, 0);
        appInfo = myApplication.getAppInfo();
        BaseUtil.makeRootDirectory(appInfo.getPath() + "/DownLoad");

        refresh = (Button) findViewById(R.id.refresh_bt_web);
        refresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 自动生成的方法存根
                myWeb.setVisibility(View.VISIBLE);
                myWeb.mreload();
            }
        });

        MAIN_URL = getIntent().getStringExtra("url");
        myWeb = (MyWeb) findViewById(R.id.myWeb1);
        myWeb.maddJS(new MyjavaScript(), "MyJS");
        myWeb.SetOnWebStaChangeListener(mChangeListener);
        myWeb.setStartInNew(false);//是否启用路由模式
        myWeb.setMAIL_URL(MAIN_URL);
        myWeb.mloadurl(MAIN_URL);
        DL_path = Environment.getExternalStorageDirectory() + "/" + appInfo.getPath() + "/DownLoad/";
        myWeb.setDL_path(DL_path);

        //更新检测线程
//        tUpdate_base = new ToolUpdate_base(this, ToolUpdate_base.AUTO, DL_path, appInfo.getUp_url(), 1, R.mipmap.ic_launcher);
//        checkUpdate(appInfo.getUp_url());
    }

    private OnWebStaChangeListener mChangeListener = new OnWebStaChangeListener() {

        @Override
        public void StaChange(int sta) {
            // TODO 自动生成的方法存根
            Log.w(TAG, "StaChange:" + sta);
            switch (sta) {
                case 1:
                    //页面报错
                    upHandler.sendEmptyMessage(5);
                    break;
                case 2:
                    //初始化离线页面
                    break;
                case 0:
                    //网络异常提示
                    baseUtil.showToast("网络异常,请检查网络链接");
                default:
                    break;
            }
        }

        @Override
        public void StaLoad(int sta) {
            // TODO 自动生成的方法存根
            Log.w(TAG, "StaLoad:" + sta);
            switch (sta) {
                case 0://开始读取
                    break;
                case 1://读取完毕
//				myWeb.mloadjs("javascript:setToken('" + XG_TOKEN + "')");
                    break;
                case 2://报错读取完毕
                    myWeb.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void StaBack(int sta) {
            // TODO 自动生成的方法存根
            IN_BACK = sta;
        }

        @Override
        public void FullScreen(int sta) {
            // TODO 自动生成的方法存根
            setRequestedOrientation(sta);
        }
    };

    private class MyjavaScript {

        /**
         * @param url
         * @Description: TODO(跳转页面)
         */
        @JavascriptInterface
        public void loadurl(String url) {
            myWeb.mloadurl(url);
        }

        /**
         * @param keys
         * @param info
         * @Description: TODO(储存信息)
         */
        @JavascriptInterface
        public void setinfo(String keys, String info) {
            SharedPreferences sp = getSharedPreferences(appInfo.getSp_name(), 0);
            sp.edit().putString(keys, info).commit();
        }

        /**
         * @param keys
         * @return
         * @Description: TODO(读取信息)
         */
        @JavascriptInterface
        public String getinfo(String keys) {
            SharedPreferences sp = getSharedPreferences(appInfo.getSp_name(), 0);
            return sp.getString(keys, "");
        }

        /**
         * @param PhoneNo
         * @Description: TODO(拨打电话)
         */
        @JavascriptInterface
        public void jsPhoneCall(String PhoneNo) {
            startActivity(new Intent("android.intent.action.CALL", Uri.parse("tel:" + PhoneNo)));
        }

        @JavascriptInterface
        public void sound() {
            pool.play(soundid, 1, 1, 0, 0, 1);
        }

        /**
         * @Description: TODO(退出应用)
         */
        @JavascriptInterface
        public void FinishApp() {
            showOutDialog();
        }

        /**
         * @Description: TODO(检测更新)
         */
        @JavascriptInterface
        public void CheckUpdate() {
            tUpdate_base.setUMODE(ToolUpdate_base.MANUAL);
            checkUpdate(appInfo.getUp_url());
        }

        /**
         * @Description: TODO(检测更新, 带地址)
         */
        @JavascriptInterface
        public void CheckUpdate2(String url) {
            tUpdate_base.setUMODE(ToolUpdate_base.MANUAL);
            checkUpdate(url);
        }

        //显示退出弹框
        @JavascriptInterface
        public void showout() {
            showOutDialog();
        }

        /**
         * @Description: TODO(初始化图片)
         */
        @JavascriptInterface
        public void initpic() {
            dataList = new ArrayList<Map<String, String>>();
            JSONObject jsonObject = new JSONObject();
            myApplication.setUpdateflag(jsonObject);
            Log.w("init", "init");
        }

        /**
         * @param picno
         * @param url
         * @Description: TODO(上传图片)
         */
        @JavascriptInterface
        public void getpic(int picno, String url) {
            myApplication.setPicno(picno);
            myApplication.setPIC_URL(url);
            Intent intent = new Intent(WebActivity.this, PicSelectActivity.class);
            intent.putExtra("dataList", dataList);
            startActivityForResult(intent, GET_PIC);
        }

        //扫描二维码
        @JavascriptInterface
        public void scan() {
            Intent i = new Intent(WebActivity.this, ScanActivity.class);
            startActivityForResult(i, GET_SCAN);
            overridePendingTransition(R.anim.in, R.anim.out);
        }

        /**
         * 分享
         *
         * @param Link 分享内容
         */
        @JavascriptInterface
        public void ShareLink(String Link) {
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Share");
            intent.putExtra(Intent.EXTRA_TEXT, Link);

            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(Intent.createChooser(intent, getTitle()));
        }

        /**
         * 发送短信
         *
         * @param tel 号码
         * @param msg 内容
         */
        @JavascriptInterface
        public void SendSMS(String tel, String msg) {
            SendMsg sendMsg = new SendMsg(WebActivity.this);
            try {
                sendMsg.sendSMS(tel, msg);
            } catch (Exception e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
                Toast.makeText(WebActivity.this, "短信发送失败！", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * @param url
         * @Description: TODO(下载文件)
         */
        @JavascriptInterface
        public void DownLoadFile(String url) {
            MWDownloadTask task = new MWDownloadTask(DL_path, WebActivity.this);
            task.execute(url);
        }

        /**
         * @param utype
         * @Description: TODO(修改用户类型)
         */
        @JavascriptInterface
        public void ChangeUserType(int utype) {
            tUpdate_base.setUserType(utype);
        }

        @JavascriptInterface
        public void startNavi(String lat, String lng, String name) {
            Toast.makeText(WebActivity.this, lat + lng + name, Toast.LENGTH_SHORT).show();
        }

        @JavascriptInterface
        public String getAccessToken() {
            return mSpUtil.getAccessToken();
        }

        @JavascriptInterface
        public void forgetJump() {
            startActivity(new Intent(WebActivity.this,LoginActivity.class));
        }

        @JavascriptInterface
        public void goBack(){
           finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (myWeb.isShowVideo()) {
                myWeb.mHideVideo();
                return true;
            }
            if (myWeb.getVisibility() == View.GONE) {
                showOutDialog();
            } else {
                if (IN_BACK == 1) {
                    try {
                        new MyjavaScript().goBack();
//                        myWeb.mloadjs("javascript:lcp_baseBack()");
                    } catch (Exception e) {
                        showOutDialog();
                    }
                }
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    //显示退出弹出框
    private void showOutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
        builder.setMessage("确认退出程序？");
        builder.setTitle("退出");
        builder.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO 自动生成的方法存根
                        dialog.dismiss();
                        finish();
                    }
                });
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO 自动生成的方法存根
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == GET_PIC) {
                dataList = (ArrayList<Map<String, String>>) data.getSerializableExtra("dataList");
                Log.d("webdata", dataList.toString());
                upHandler.sendEmptyMessage(3);
            } else if (requestCode == GET_SCAN) {
                String info = data.getStringExtra("scan");//二维码内容
                myWeb.mloadjs("javascript:getEwm('" + info + "')");
            }
        }
    }


    private Handler upHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 3:
                    StringBuffer info = new StringBuffer();
                    info.append("'");
                    for (int i = 0; i < dataList.size(); i++) {
                        info.append(dataList.get(i).get("upname"));
                        if (i != dataList.size() - 1) {
                            info.append(",");
                        }
                    }
                    info.append("'");
                    myWeb.mloadjs("javascript:lcp_setImg(" + info + ")");
                    break;
                case 5:
                    myWeb.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
    };

    private void checkUpdate(String upurl) {
        if (appInfo.getUpmode() == 1) {
            UpdateTask upTask = new UpdateTask(Environment.getExternalStorageDirectory() + "/" + appInfo.getPath()
                    + "/DownLoad/", this);
            upTask.execute(new String[]{upurl, baseUtil.getVersion()});
        } else {
            tUpdate_base.setD_path(upurl);
            tUpdate_base.checkVer();
        }
    }


}
